<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Repositories\MemberRepositoryEloquent;
use App\User;
use App\Models\BankCard;
use App\Models\Withdrawals;
//use App\Models\UserRelationship;
use Breadcrumbs, Hash,Auth,Toastr,Config,Validator,DB,Carbon;
use Illuminate\Http\Request;
use App\Http\Requests\Home\User\UpdatePasswordRequest;
use App\Models\FinancialDetails;

use EasyWeChat\Payment\Order;

class WithdrawalsController extends Controller{

    protected $user;

    public function __construct(MemberRepositoryEloquent $user)
    {
        //parent::__construct();
        $this->user = $user;


    }

    public function index(Request $request){
        $user = $request->user();
        $bankCard = BankCard::where('user_id','=',$user->id)->where('status','=',1)->orderBy('id','desc')->first();
        //var_dump($bankCard);
        return view('home.withdrawals.add',compact('user','bankCard'));
    }

    public function withdrawals(Request $request){
        $validator = Validator::make($request->all(), [
            'money' => 'required|numeric|min:100',
        ]);
        $user=$request->user();
        $money = $request->money;
        $validator->after(function($validator) use ($user,$money) {
            
            //判断余额是否足够
            if($user->balance<$money){
                $validator->errors()->add('money', '余额不足!');
            }
            //判断银行卡是否有选择
            $bankCard = BankCard::where('user_id','=',$user->id)->where('status','=',1)->orderBy('id','desc')->first();
            if(!$bankCard){
                $validator->errors()->add('money', '请先选择银行卡!');
            }
        });

        if ($validator->fails()) {
            //dd($validator->errors());
            return redirect()->back()
                        ->withErrors($validator)
                        ->withInput();
        }

        //
        $fee = $money*0.01;
        if($fee<2){
            $fee = 2;
        }
        $note = '账户提现:￥'.$money.'(实际到账:'.($money-$fee).'手续费:￥'.$fee.')';
        DB::beginTransaction();
        try{ 
            $result = $this->user->modifyBalance($user->id,-$money,2,$note,$money);
            if($result){
                $bankCard = BankCard::where('user_id','=',$user->id)->where('status','=',1)->orderBy('id','desc')->first();
                $partner_trade_no = date('YmdHis').$user->id.rand(100,999);
                $withdrawals = Withdrawals::create([
                        'user_id'=>$user->id,
                        'real_name'=>$bankCard['real_name'],
                        'bank_name'=>$bankCard['bank_name'],
                        'address'=>$bankCard['address'],
                        'accounts_bank'=>$bankCard['accounts_bank'],
                        'card_number'=>$bankCard['card_number'],
                        'money'=>$money-$fee,
                        'fee'=>$fee,
                        'partner_trade_no'=>$partner_trade_no
                ]);
                if($withdrawals){
                    //return response()->view('home.withdrawals.add', $data)->header('Content-Type', $type);
                    $return = redirect()->back()
                            ->with(['msg'=>'申请提现成功！']);
                            
                }else{
                    $return = redirect()->back()
                            ->with(['msg'=>'申请提现失败！']);
                }
            }
            DB::commit(); 
            return $return;
        }catch (\Exception $e) {

            DB::rollBack(); 
            return  redirect()->back()
                            ->with(['msg'=>'申请提现失败！']);
        }
    }

    public function banklist(Request $request){
        $user = $request->user();
        $banks = BankCard::where('user_id','=',$user->id)->orderBy('id','desc')->get();
        return view('home.withdrawals.banklist',compact('banks'));
    }

    public function cashing(){
        return view('home.withdrawals.cashing');
    }

    public function currentBank(Request $request,$bankid=null){
        $user = $request->user();
        if($bankid){
            $bankCard = BankCard::where('status','!=',1)->where('user_id','=',$user->id)->where('id','=',$bankid)->first();
            if($bankCard){
                BankCard::where('user_id','=',$user->id)->where('status','=',1)->update(['status'=>0]);
                $bankCard->status=1;
                $bankCard->save();
            }
        }
        return redirect('/withdrawals');
    }

    public function deleteBank(Request $request){
        $user = $request->user();
        $bankid = $request->bankid;
        $bank = BankCard::find($bankid);
        if($bank->user_id == $user->id){
            $res = $bank->delete();
            if($res){
                return response()->json(['status'=>1,'msg'=>'解绑成功'], 200);
            }
        }
        
        return response()->json(['status'=>0,'msg'=>'解绑失败'], 200);
    }

    public function storeBank(Request $request){
        $user = $request->user();
        //var_dump($request->all());
        $messages = [
            'required' => '不能为空',
            'regex'=>  '不是有效的银行卡'
        ];
        $validator = Validator::make($request->all(), [
            'real_name' => 'required',
            'bank_name'=>'required',
            'address'=>'required',
            'accounts_bank'=>'required',
            'card_number'=>'required|regex:/^(\d{16,19})$/',
        ],$messages);
        if ($validator->fails()) {
            //dd($validator->errors());
            return redirect('/withdrawals/cashing')
                        ->withErrors($validator)
                        ->withInput();
        }

        $card = BankCard::create([
                    'user_id'=>$user->id,
                    'real_name'=>$request['real_name'],
                    'bank_name'=>$request['bank_name'],
                    'address'=>$request['address'],
                    'accounts_bank'=>$request['accounts_bank'],
                    'card_number'=>$request['card_number'],
        ]);
        return redirect('/withdrawals/cashing');            

    }
}